﻿using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
/*
Asp.Net无组件多文件上传类(1.0.0.0)
*/
namespace Jxym.Tools.MyFile
{
    /// <summary>
    /// 文件结构
    /// </summary>
    public struct UpLoad_MyFileInfo
    {
        public string OldFileName { get; set; }
        public string ServerFileName { get; set; }
        public int FileSize { get; set; }
        public string FileExt { get; set; }
        public string FileKeyName { get; set; }
        public string FileErrorInfo { get; set; }
    }

    /// <summary>
    /// 文件上传类
    /// </summary>
    public class UpLoad
    {
        #region 变量申明

        private string allowExts = "";//默认的可以上传的文件扩展名称
        private string rootPath = "";//文件保存的目录
        private bool isExtClass = false;
        private IList<UpLoad_MyFileInfo> _fileInfo_List = null;

        #endregion

        #region 属性

        /// <summary>
        /// 是否按扩展名分类存储
        /// </summary>
        public bool IsExtClass
        {
            get { return isExtClass; }
            set { isExtClass = value; }
        }

        /// <summary>
        /// 默认的可以上传的文件扩展名称[分隔符“|”]
        /// </summary>
        public string AllowExts
        {
            get { return allowExts; }
            set { allowExts = value; }
        }

        /// <summary>
        /// 文件保存的目录[相对路径]
        /// </summary>
        public string RootPath
        {
            get { return rootPath; }
            set { string tempPath = value; rootPath = HttpContext.Current.Server.MapPath(tempPath); }
        }

        /// <summary>
        /// 上传文件的返回信息集合
        /// </summary>
        public IList<UpLoad_MyFileInfo> ReturnUpLoadFileInfo_List
        {
            get { return _fileInfo_List; }
        }

        #endregion

        public UpLoad()
        {
            this.allowExts = "";
            this.rootPath = HttpContext.Current.Server.MapPath("/UpFiles/");
            this.isExtClass = false;
        }




        /// <summary>
        /// 以当前时间加随机数生成文件名
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string getNewDateFileName(HttpPostedFile file)
        {
            Random r = new Random();
            int sjs = r.Next(0, 100);
            return DateTime.Now.ToFileTime() + "_" + sjs + "." + getExt(file);
        }

        /// <summary>
        /// 保存文件到磁盘
        /// </summary>
        public void Save()
        {
            try
            {
                _fileInfo_List = new List<UpLoad_MyFileInfo>();

                HttpFileCollection files = HttpContext.Current.Request.Files;

                for (int i = 0; i < files.Count; i++)
                {
                    UpLoad_MyFileInfo fileInfo = new UpLoad_MyFileInfo();

                    HttpPostedFile file = files.Get(i);

                    if (file.ContentLength > 0)
                    {
                        string ext = getExt(file);

                        if (checkExt(ext))
                        {
                            try
                            {
                                string path = this.rootPath;
                                if (this.isExtClass)
                                    path += ext + "\\";
                                else
                                    path += "\\";

                                string newfilename = getNewDateFileName(file);

                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }
                                file.SaveAs(path + newfilename);
                                fileInfo.FileKeyName = files.GetKey(i);
                                fileInfo.ServerFileName = newfilename;
                                fileInfo.FileSize = file.ContentLength;
                                fileInfo.FileExt = ext;

                            }
                            catch (Exception ex)
                            {
                                fileInfo.FileErrorInfo = ex.Message;
                            }
                        }
                        else
                        {
                            fileInfo.FileErrorInfo = "不支持的扩展名";
                        }
                    }
                    _fileInfo_List.Add(fileInfo);
                }
            }
            catch (Exception e1)
            {
                throw new Exception(e1.Message);
            }
        }

        /// <summary>
        /// 获取文件的扩展名称
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string getExt(HttpPostedFile file)
        {
            char[] cs = file.FileName.ToCharArray();
            int l = 0;
            string ext = "";
            for (int i = cs.Length - 1; i >= 0; i--) { if (cs[i] == '.') { l = i; } }
            for (int i = l + 1; i < cs.Length; i++)
            {
                ext += cs[i];
            }
            return ext;
        }

        /// <summary>
        /// 验证扩展名是否支持
        /// </summary>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        private bool checkExt(string fileExt)
        {
            if (this.allowExts == "")
                return true;

            string[] exts = allowExts.Split('|');
            foreach (string ext in exts)
            {
                if (ext.ToUpper().Equals(fileExt.ToUpper()))
                    return true;
            }
            return false;
        }
    }
}
